import { query } from '../../config/database';

// 基础模型类，提供通用的数据库操作方法
export abstract class BaseModel {
  protected tableName: string;
  
  constructor(tableName: string) {
    this.tableName = tableName;
  }
  
  // 查找单个记录
  async findById(id: string): Promise<any> {
    const result = await query(
      `SELECT * FROM ${this.tableName} WHERE id = $1`,
      [id]
    );
    return result.rows[0] || null;
  }
  
  // 查找所有记录
  async findAll(options: {
    limit?: number;
    offset?: number;
    orderBy?: string;
    orderDirection?: 'ASC' | 'DESC';
    where?: Record<string, any>;
  } = {}): Promise<any[]> {
    let sql = `SELECT * FROM ${this.tableName}`;
    const params: any[] = [];
    let paramIndex = 1;
    
    // 添加WHERE条件
    if (options.where && Object.keys(options.where).length > 0) {
      const whereConditions = Object.keys(options.where).map(key => {
        params.push(options.where![key]);
        return `${key} = $${paramIndex++}`;
      });
      sql += ` WHERE ${whereConditions.join(' AND ')}`;
    }
    
    // 添加排序
    if (options.orderBy) {
      sql += ` ORDER BY ${options.orderBy} ${options.orderDirection || 'ASC'}`;
    }
    
    // 添加分页
    if (options.limit) {
      sql += ` LIMIT $${paramIndex++}`;
      params.push(options.limit);
    }
    
    if (options.offset) {
      sql += ` OFFSET $${paramIndex++}`;
      params.push(options.offset);
    }
    
    const result = await query(sql, params);
    return result.rows;
  }
  
  // 创建记录
  async create(data: Record<string, any>): Promise<any> {
    const keys = Object.keys(data);
    const values = Object.values(data);
    const placeholders = keys.map((_, index) => `$${index + 1}`).join(', ');
    
    const sql = `
      INSERT INTO ${this.tableName} (${keys.join(', ')})
      VALUES (${placeholders})
      RETURNING *
    `;
    
    const result = await query(sql, values);
    return result.rows[0];
  }
  
  // 更新记录
  async update(id: string, data: Record<string, any>): Promise<any> {
    const keys = Object.keys(data);
    const values = Object.values(data);
    const setClause = keys.map((key, index) => `${key} = $${index + 2}`).join(', ');
    
    const sql = `
      UPDATE ${this.tableName}
      SET ${setClause}
      WHERE id = $1
      RETURNING *
    `;
    
    const result = await query(sql, [id, ...values]);
    return result.rows[0];
  }
  
  // 删除记录
  async delete(id: string): Promise<boolean> {
    const result = await query(
      `DELETE FROM ${this.tableName} WHERE id = $1`,
      [id]
    );
    return result.rowCount > 0;
  }
  
  // 统计记录数
  async count(where?: Record<string, any>): Promise<number> {
    let sql = `SELECT COUNT(*) as count FROM ${this.tableName}`;
    const params: any[] = [];
    let paramIndex = 1;
    
    if (where && Object.keys(where).length > 0) {
      const whereConditions = Object.keys(where).map(key => {
        params.push(where[key]);
        return `${key} = $${paramIndex++}`;
      });
      sql += ` WHERE ${whereConditions.join(' AND ')}`;
    }
    
    const result = await query(sql, params);
    return parseInt(result.rows[0].count, 10);
  }
  
  // 检查记录是否存在
  async exists(id: string): Promise<boolean> {
    const result = await query(
      `SELECT 1 FROM ${this.tableName} WHERE id = $1 LIMIT 1`,
      [id]
    );
    return result.rows.length > 0;
  }
  
  // 批量插入
  async bulkCreate(dataArray: Record<string, any>[]): Promise<any[]> {
    if (dataArray.length === 0) return [];
    
    const keys = Object.keys(dataArray[0]);
    const placeholders = dataArray.map((_, rowIndex) => {
      const rowPlaceholders = keys.map((_, colIndex) => 
        `$${rowIndex * keys.length + colIndex + 1}`
      ).join(', ');
      return `(${rowPlaceholders})`;
    }).join(', ');
    
    const values = dataArray.flatMap(data => Object.values(data));
    
    const sql = `
      INSERT INTO ${this.tableName} (${keys.join(', ')})
      VALUES ${placeholders}
      RETURNING *
    `;
    
    const result = await query(sql, values);
    return result.rows;
  }
  
  // 执行原始SQL查询
  async raw(sql: string, params?: any[]): Promise<any> {
    return await query(sql, params);
  }
}